package com.nowcoder.community.dao;

import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.util.RedisKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class CommonRedisDao {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    public void setCaptcha(String id, String val, int expireSeconds) {
        redisTemplate.opsForValue().set(RedisKeyUtils.getCaptchaKey(id), val, expireSeconds, TimeUnit.SECONDS);
    }

    public String getCaptcha(String id) {
        return (String) redisTemplate.opsForValue().get(RedisKeyUtils.getCaptchaKey(id));
    }

    public void setLoginTicket(String ticket, LoginTicket loginTicket, int expireSeconds) {
        redisTemplate.opsForValue().set(RedisKeyUtils.getLoginTicketKet(ticket), loginTicket, expireSeconds, TimeUnit.SECONDS);
    }

    public LoginTicket getLoginTicket(String ticket) {
        return (LoginTicket) redisTemplate.opsForValue().get(RedisKeyUtils.getLoginTicketKet(ticket));
    }

    public void setUser(int id, User user, int expireSeconds) {
        redisTemplate.opsForValue().set(RedisKeyUtils.getUserKey(id), user, expireSeconds, TimeUnit.SECONDS);
    }

    public User getUserById(int id) {
        return (User) redisTemplate.opsForValue().get(RedisKeyUtils.getUserKey(id));
    }

    public void delLoginTicket(String ticket) {
        redisTemplate.delete(RedisKeyUtils.getLoginTicketKet(ticket));
    }

    public void delUserById(int id) {
        redisTemplate.delete(RedisKeyUtils.getUserKey(id));
    }

    public void setUserLikeHistory(int userId, int entityId) {
        redisTemplate.opsForSet().add(RedisKeyUtils.getUserLikeHistoryKey(userId), entityId);
    }

    public boolean hasLikedHistory(int userId, int entityId) {
        return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(RedisKeyUtils.getUserLikeHistoryKey(userId), entityId));
    }

    public void setUserFollowHistory(int followerId, int userId) {
        redisTemplate.opsForSet().add(RedisKeyUtils.getUserFollowHistoryKey(userId), followerId);
    }

    public boolean hasFollowedHistory(int userId, int entityId) {
        return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(RedisKeyUtils.getUserFollowHistoryKey(userId), entityId));
    }
}
